package com.example.dishit.view.friendmaint;

import java.util.List;

import com.example.dishit.R;
import com.example.dishit.controller.friendmaint.FriendMaintController;
import com.example.dishit.controller.main.MainController;
import com.example.dishit.model.dbproxy.DBProxyFactory;
import com.example.dishit.model.dbproxy.IDBProxyCallback;
import com.example.dishit.model.dish.DishData;

import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FriendMaintDialogFragment extends DialogFragment {
    private ArrayAdapter<String> arrayAdapter;
    
    public FriendMaintDialogFragment() {}
    
    public void setArrayAdapter(final ArrayAdapter<String> arrayAdapter) {
        this.arrayAdapter = arrayAdapter;
    }
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        super.onCreateDialog(savedInstanceState);
        
        final Dialog dialog = new Dialog(getActivity());
        
        dialog.setContentView(R.layout.dialog_add_user);
        dialog.setTitle("Disher to add:");
        final Button okButton = (Button)dialog.findViewById(R.id.dialog_add_user_button);
        final EditText editText = (EditText)dialog.findViewById(R.id.dialog_add_user_text);
        okButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View arg0) {
                final String userToAdd = editText.getText().toString();
                DBProxyFactory.instance().followerUser(MainController.THIS_USER_ID, userToAdd, new IDBProxyCallback() {
                    public void onDishersCallback(List<String> myDishers) {}
                    public void onDishDataCallback(List<DishData> dishDatas) {}
                    public void onResultCallback(final boolean wasSuccessful, final String message) {
                        arg0.post(new Runnable() {
                            public void run() {
                                if(wasSuccessful) {
                                    arrayAdapter.insert(userToAdd, 0);
                                    Toast.makeText(dialog.getContext(), "Added " + userToAdd + ".", Toast.LENGTH_LONG) .show();
                                    FriendMaintController.instance().clearSelections();
                                } else {
                                    Toast.makeText(dialog.getContext(), "Failed to add " + userToAdd + ":    " + message, Toast.LENGTH_LONG) .show();
                                }
                                dialog.cancel();
                            }
                        });
                    }
                });
            }
        });
        return dialog;
    }
}
